//
//  RootViewController.m
//  TestTableView
//
//  Created by wenshuishi on 12-11-14.
//  Copyright (c) 2012年 wenshuishi. All rights reserved.
//

#import "RootViewController.h"
#import <QuartzCore/CALayer.h>
#import "AppDelegate.h"
#import "NewManViewController.h"
//#import "GameViewController.h"
//#import "O2OGameViewController.h"
#import "LeftViewController.h"

extern BOOL isInTimeTalking;
@interface RootViewController ()

@end


@implementation RootViewController
@synthesize currViewController = _currViewController;
@synthesize curSlideRecognizer;

-(id)initWithLeftViewController:(UIViewController*)leftVC rightViewController:(UIViewController*)rightVC {
    self = [super init];
    leftViewController = [leftVC retain];
    rightViewController = [rightVC retain];
    return self;
}
-(id)initWithRightViewController:(UIViewController*)rightVC challenge:(BOOL)challenge{
    self = [super init];
    isChallenge = challenge;
    rightViewController = [rightVC retain];
    return self;
}
-(UIViewController*)getleftVC{
    return leftViewController;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"RootViewController viewDidLoad ");
    
    self.view.userInteractionEnabled = YES;
    
    bgTapView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)] autorelease];
    [self.view addSubview:bgTapView];
    
    [self.view addSubview:rightViewController.view];
    
//    if (OS_VERSION >= 5) {//去掉，不然ios5一下不会调用rightViewController viewWillDisappear
//        [rightViewController performSelector:@selector(viewWillDisappear:) withObject:@"1" afterDelay:.5];
//    }
    
    rightViewController.view.hidden = YES;
    
    [self.view addSubview:leftViewController.view];
    
    LeftViewController *leftViewCtrl = (LeftViewController *)leftViewController;
    [leftViewCtrl setParentView:self];
    
    UITapGestureRecognizer *tapRecognizer = [[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTap:)] autorelease];
    [bgTapView addGestureRecognizer:tapRecognizer];
    bgTapView.userInteractionEnabled = NO;
    
    prevTouchPoint = CGPointMake(0, 0);
    
    //下面2句为了让currentView在停靠被拖回的时候用到，当currentView停靠的时候，要可以再滑动出来
    UIPanGestureRecognizer *slideRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onSlide:)] autorelease];
    [bgTapView addGestureRecognizer:slideRecognizer];
    
    [self performSelector:@selector(showCurrentView)];
    
    if (leftViewController) {
//        [self performSelector:@selector(showLeftViewController) withObject:nil afterDelay:0.3];//现在不要求向左滑动
//        [self performSelector:@selector(showRightView) withObject:nil afterDelay:1];
    }else{
//        if (OS_VERSION < 5.0) {//for bug 473
//            [rightViewController performSelector:@selector(viewWillAppear:) withObject:@"1"];
//        }
//        bgTapView.userInteractionEnabled = YES;
    }
}


-(void)showCurrentView {
    UIViewController *viewC = [[[NewManViewController alloc] init] autorelease];
    UINavigationController *navController = [[[UINavigationController alloc] initWithRootViewController:viewC] autorelease];
    self.currViewController = navController;
    
    self.curSlideRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onSlide:)] autorelease];
    [self.currViewController.view addGestureRecognizer:self.curSlideRecognizer];
    CGRect rect = self.currViewController.view.frame;
    self.currViewController.view.frame = rect;
    
    if ([[[UIDevice currentDevice] systemVersion] floatValue] <= 5.0){
        [viewC viewWillAppear:YES];
    }
    [self.view addSubview:self.currViewController.view];
}

-(void)showLeftViewController {
    //添加侧边阴影
    [self addShadowTo:_currViewController];
    [UIView animateWithDuration:0.5 animations:^{
        CGRect rect=_currViewController.view.frame;
        rect.origin.x=self.view.frame.size.width-LEFT_DOCK_WIDTH;
        _currViewController.view.frame=rect;
        _currViewController.view.userInteractionEnabled=NO;
    } completion:^(BOOL finished) {
        self.view.userInteractionEnabled = YES;//动画完成以后才允许点击 added by youq 1028
        bgTapView.userInteractionEnabled = YES;
        [leftViewController viewWillAppear:YES];
    }];
}


- (void)onTap:(UITapGestureRecognizer*)gesture {
    //bgView被点击
    bgTapView.userInteractionEnabled=NO;
    self.view.userInteractionEnabled = NO;
    
    if (_currViewController) {
        CGPoint point=[gesture locationInView:_currViewController.view];
        if (point.x > 300) {
//            [NC postNotificationName:NOTI_ON_TAP_SWITCH object:nil];//added by youq 右边切换
        }
        
        if (point.x<0 || point.x>_currViewController.view.frame.size.width) {
            self.view.userInteractionEnabled = YES;
            return;
        }
        [UIView animateWithDuration:0.3 animations:^(void) {
            CGRect frame=_currViewController.view.frame;
            frame.origin.x=0;
            _currViewController.view.frame=frame;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            _currViewController.view.userInteractionEnabled = YES;
            [leftViewController viewWillDisappear:YES];
            [rightViewController viewWillDisappear:YES];
        }];
    }
}
//返回到中间界面
-(void)backToMidView{
    bgTapView.userInteractionEnabled = NO;
    self.view.userInteractionEnabled = NO;
    if (_currViewController) {
        [UIView animateWithDuration:0.3 animations:^(void) {
            CGRect frame=_currViewController.view.frame;
            frame.origin.x=0;
            _currViewController.view.frame=frame;
        } completion:^(BOOL finished) {
            self.view.userInteractionEnabled = YES;
            _currViewController.view.userInteractionEnabled = YES;
            [leftViewController viewWillDisappear:YES];
            [rightViewController viewWillDisappear:YES];
        }];
    }
}


- (void)onSlide:(UIPanGestureRecognizer*)gesture {
    CGPoint curr = [gesture locationInView:self.view];
    BOOL ifToLeft = [gesture translationInView:self.view].x < 0;
//    NSLog(@"dafasd %d %f ", ifToLeft, _currViewController.view.frame.origin.x);
//    if (!ifToLeft && !leftViewController && _currViewController.view.frame.origin.x>=0) {
//        return;
//    }
    if (ifToLeft && _currViewController.view.frame.origin.x<=0) {
        return;
    }
    if (gesture.state == UIGestureRecognizerStateChanged) {
        if (curr.x != prevTouchPoint.x) {
            CGRect frame = _currViewController.view.frame;
            frame.origin.x += curr.x-prevTouchPoint.x;
            if (frame.origin.x > 0 && !leftViewController) {
                frame.origin.x = 0;
            }
            _currViewController.view.frame = frame;
            if (_currViewController.view.frame.origin.x > 0) {
                leftViewController.view.hidden = NO;
                rightViewController.view.hidden = YES;
            } else {
                rightViewController.view.hidden = NO;
                leftViewController.view.hidden = YES;
            }
        }
    } else if (gesture.state == UIGestureRecognizerStateEnded) {
        UIView *v = _currViewController.view;
        [UIView animateWithDuration:0.2 animations:^(void) {
            CGFloat x = 0;
            if (v.frame.origin.x>80 && ifToLeft==NO) {
                x = self.view.frame.size.width-LEFT_DOCK_WIDTH;
                v.userInteractionEnabled=NO;
                bgTapView.userInteractionEnabled=YES;
            } else if (v.frame.origin.x<240 && ifToLeft==YES) {
                if (v.frame.origin.x>0) {
                    x = 0;
                    bgTapView.userInteractionEnabled=NO;
                    v.userInteractionEnabled=YES;
                } else {
                    if (v.frame.origin.x+v.frame.size.width<240 && ifToLeft==YES) {
                        x = -(self.view.frame.size.width-DEFAULT_DOCK_WIDTH);
                        v.userInteractionEnabled=NO;
                        bgTapView.userInteractionEnabled=YES;
                    }
                }
            } else if (v.frame.origin.x+v.frame.size.width>80 && ifToLeft==NO) {
                x = 0;
//                [NC postNotificationName:NOTI_ATOTHER_KEYBOARD_HIDE object:nil];//added by youq 0904
//                [NC postNotificationName:NOTI_ON_TAP_SWITCH object:nil];//added by youq 0904 右边切换离开广场
                bgTapView.userInteractionEnabled=NO;
                v.userInteractionEnabled=YES;
            } else {
                x = 0;
//                [NC postNotificationName:NOTI_ATOTHER_KEYBOARD_HIDE object:nil];//added by youq 0904
                bgTapView.userInteractionEnabled=NO;
                v.userInteractionEnabled=YES;
            }
            CGRect frame = v.frame;
            frame.origin.x = x;
            v.frame = frame;
        } completion:^(BOOL finished) {
            if (_currViewController.view.frame.origin.x > 0) {
                [leftViewController viewWillAppear:YES];
                [rightViewController viewWillDisappear:YES];
            } else if (_currViewController.view.frame.origin.x == 0) {
                [leftViewController viewWillDisappear:YES];
                [rightViewController viewWillDisappear:YES];
//                [NC postNotificationName:NOTI_ON_TAP_SWITCH object:nil];//added by youq 右边切换离开广场
            } else {
                [leftViewController viewWillDisappear:YES];
                [rightViewController viewWillAppear:YES];
//                [NC postNotificationName:NOTI_SHOW_RIGHT_VIEW object:nil];//added by youq 0409
            }
            leftViewController.view.frame = RECT(0, 0, SCREEN_WIDTH-LEFT_DOCK_WIDTH, FH(leftViewController.view));//for bug 0109
        }];
    }
    //for bug 0109
    if (!ifToLeft) {
        if (_currViewController.view.frame.origin.x > SCREEN_WIDTH-LEFT_DOCK_WIDTH) {
            leftViewController.view.frame = RECT(0, 0, _currViewController.view.frame.origin.x, FH(leftViewController.view));
        }
    }
    
//    NSLog(@"*******  %f", _currViewController.view.frame.origin.x);
    prevTouchPoint = curr;
}

-(void)addShadowTo:(UIViewController*)viewController {
    
    viewController.view.layer.shadowOpacity = 0.8f;
    viewController.view.layer.cornerRadius = 4.0f;
    viewController.view.layer.shadowOffset = CGSizeZero;
    viewController.view.layer.shadowRadius = 4.0f;
    viewController.view.layer.shadowPath = [UIBezierPath bezierPathWithRect:self.view.bounds].CGPath;
    
}


-(void)showViewController:(UIViewController*)viewController {
    if (_currViewController==viewController) {
        return;
    }
    if (_currViewController!=nil) {
        [_currViewController.view removeFromSuperview];
        //下面尝试释放资源:某些界面，可能存在定时器，此时应该实现‘releaseResources’函数，在里面停用计时器
        if ([_currViewController isMemberOfClass:[UINavigationController class]]) {
            UINavigationController *navi=(UINavigationController*)_currViewController;
            for (UIViewController *vc in navi.viewControllers) {
                if ([vc respondsToSelector:@selector(releaseResources)]) {
                    [vc performSelector:@selector(releaseResources)];
                }
            }
        } else {
            if ([_currViewController respondsToSelector:@selector(releaseResources)]) {
                [_currViewController performSelector:@selector(releaseResources)];
            }
        }
        self.currViewController=nil;
    }
    
    self.currViewController=viewController;
    
    if (_currViewController.view.layer.shadowOpacity!=0.8f) {
        //添加侧边阴影
        [self addShadowTo:_currViewController];
    }
    
    self.curSlideRecognizer = [[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onSlide:)] autorelease];
    [viewController.view addGestureRecognizer:self.curSlideRecognizer];
    
    __block CGRect frame = self.view.bounds;
    if ([leftViewController.view superview]) {
        frame.origin.x=320-LEFT_DOCK_WIDTH;
    } else {
        frame.origin.x=-(320-LEFT_DOCK_WIDTH);
    }
//    if (frame.size.height >= SCREEN_HEIGHT) {
//        frame.origin.y = -20;
//    }
    viewController.view.frame=frame;
    
    
    if (OS_VERSION<5 && [viewController isMemberOfClass:[UINavigationController class]]) {
        //为了解决在os4下面，viewWillAppear:等函数不调用的问题。
        AppDelegate *appDele=(AppDelegate*)[[UIApplication sharedApplication] delegate];
        [appDele.window addSubview:viewController.view];
    }
    
    [self.view addSubview:viewController.view];
    
    self.view.userInteractionEnabled = NO;
    [UIView animateWithDuration:0.3 animations:^(void) {
        frame.origin.x = 0;
        viewController.view.frame = frame;
    }completion:^(BOOL finished) {
        self.view.userInteractionEnabled = YES;
    }];
}

-(void)pushViewController:(UIViewController*)viewController {
    if (_currViewController) {
        UINavigationController *currNavi=nil;
        if ([_currViewController isMemberOfClass:[UINavigationController class]]) {
            currNavi=(UINavigationController*)_currViewController;
        } else {
            currNavi=_currViewController.navigationController;
        }
        
        UIViewController *prevController=currNavi.topViewController;
        BOOL needToPush=YES;
        UIViewController *wantToPushViewController=nil;
        if ([prevController respondsToSelector:@selector(hashCode)]) {
            
            if ([viewController isMemberOfClass:[UINavigationController class]]) {
                wantToPushViewController=((UINavigationController*)_currViewController).topViewController;
            } else {
                wantToPushViewController=viewController;
            }
            if ([wantToPushViewController respondsToSelector:@selector(hashCode)]) {
                NSString *hashCode1=[prevController performSelector:@selector(hashCode)];
                NSString *hashCode2=[wantToPushViewController performSelector:@selector(hashCode)];
                if ([hashCode1 isEqualToString:hashCode2]) {
                    needToPush=NO;
                }
            }
        }
        
        __block CGRect frame = _currViewController.view.frame;
        if (frame.origin.x<0) {//当请求push的时候，如果此时是缩到左边的状态，就移到中间
            if (needToPush) {
                if (OS_VERSION<5) {
                    //为了解决在os4下面，viewWillAppear:等函数不调用的问题。
                    [wantToPushViewController viewWillAppear:YES];
                }
                [currNavi pushViewController:viewController animated:NO];
            }
            _currViewController.view.frame=frame;
            [UIView animateWithDuration:0.3 animations:^(void) {
                frame.origin.x = 0;
                _currViewController.view.userInteractionEnabled=YES;
                bgTapView.userInteractionEnabled=NO;
                _currViewController.view.frame=frame;
            }];
        } else {
            if (needToPush) {
                if (OS_VERSION<5) {
                    //为了解决在os4下面，viewWillAppear:等函数不调用的问题。
                    [wantToPushViewController viewWillAppear:YES];
                }
                [currNavi pushViewController:viewController animated:YES];
            }
        }
    }
}


-(BOOL)checkIfSameViewController:(UIViewController*)vc1 viewController2:(UIViewController*)vc2 {
    UIViewController *tempVc1=nil,*tempVc2=nil;
    if ([vc1 isMemberOfClass:[UINavigationController class]]) {
        tempVc1=((UINavigationController*)vc1).topViewController;
    } else {
        tempVc1=vc1;
    }
    
    if ([vc2 isMemberOfClass:[UINavigationController class]]) {
        tempVc2=((UINavigationController*)vc2).topViewController;
    } else {
        tempVc2=vc2;
    }
    
    if ([tempVc1 respondsToSelector:@selector(hashCode)] && [tempVc2 respondsToSelector:@selector(hashCode)]) {
        if ([[tempVc1 performSelector:@selector(hashCode)] isEqualToString:[tempVc2 performSelector:@selector(hashCode)]]) {
            return YES;
        }
    }
    return NO;
}
//点击左上角按钮
-(void)showLeftView {
    __block CGRect frame = _currViewController.view.frame;
    _currViewController.view.frame = frame;
    
    _currViewController.view.userInteractionEnabled = NO;
    bgTapView.userInteractionEnabled = YES;
    
    //显示左边view。隐藏右边view
    leftViewController.view.hidden = NO;
    [leftViewController viewWillAppear:YES];
    rightViewController.view.hidden = YES;
    [rightViewController viewWillDisappear:YES];
    
    self.view.userInteractionEnabled = NO;//防止动画效果未完成的时候用户多次点击
    [UIView animateWithDuration:0.3 animations:^(void) {
        frame.origin.x = self.view.frame.size.width-LEFT_DOCK_WIDTH;
        _currViewController.view.frame = frame;
    }completion:^(BOOL finished) {
        self.view.userInteractionEnabled = YES;
    }];
}
//点击右上角按钮
-(void)showRightView {
    __block CGRect frame = _currViewController.view.frame;
    _currViewController.view.frame = frame;
    
    _currViewController.view.userInteractionEnabled = NO;
    bgTapView.userInteractionEnabled = YES;
    
    //显示右边view。隐藏左边view
    rightViewController.view.hidden = NO;
    [rightViewController viewWillAppear:YES];
    leftViewController.view.hidden = YES;
    [leftViewController viewWillDisappear:YES];
    
    self.view.userInteractionEnabled = NO;//防止动画效果未完成的时候用户多次点击
    [UIView animateWithDuration:0.3 animations:^(void) {
        frame.origin.x = -(self.view.frame.size.width-DEFAULT_DOCK_WIDTH);
        _currViewController.view.frame=frame;
    }completion:^(BOOL finished) {
        self.view.userInteractionEnabled = YES;
    }];
}
-(void)showAllRightView{
    //    if (!leftViewController) {
    __block CGRect frame = _currViewController.view.frame;
    _currViewController.view.frame = frame;
//    
//    _currViewController.view.userInteractionEnabled = NO;
    bgTapView.userInteractionEnabled = NO;
    
    leftViewController.view.hidden = YES;
    [leftViewController viewWillDisappear:YES];
    rightViewController.view.hidden = NO;
    [rightViewController viewWillAppear:YES];
//
//    //显示右边view。隐藏左边view
//    rightViewController.view.hidden = NO;
//    [rightViewController viewWillAppear:YES];
//    leftViewController.view.hidden = YES;
//    [leftViewController viewWillDisappear:YES];
//    
//    self.view.userInteractionEnabled = NO;//防止动画效果未完成的时候用户多次点击
    
    [UIView animateWithDuration:0.3 animations:^(void) {
        frame.origin.x = -(self.view.frame.size.width);
        _currViewController.view.frame=frame;
    }completion:^(BOOL finished) {
//        self.view.userInteractionEnabled = YES;
    }];
    //    }
}
//点击右上角按钮
-(void)onlyShowRightView {
    __block CGRect frame = _currViewController.view.frame;
    _currViewController.view.frame = frame;
    _currViewController.view.userInteractionEnabled = NO;
//    self.view.userInteractionEnabled = NO;//防止动画效果未完成的时候用户多次点击
    [UIView animateWithDuration:0.3 animations:^(void) {
        frame.origin.x = -(self.view.frame.size.width-DEFAULT_DOCK_WIDTH);
        _currViewController.view.frame=frame;
    }completion:^(BOOL finished) {
        bgTapView.userInteractionEnabled = YES;
//        self.view.userInteractionEnabled = YES;
    }];
}

//-(void)freshSizeAndPos{
//    if (isInTimeTalking) {
//        if (leftViewController.view.frame.origin.y==0) {
//            leftViewController.view.frame = CGRectMake(leftViewController.view.frame.origin.x, 0, leftViewController.view.frame.size.width, SCREEN_HEIGHT-20);
//        }
//        if (_currViewController.view.frame.origin.y==0) {
//            _currViewController.view.frame = CGRectMake(_currViewController.view.frame.origin.x, 0, _currViewController.view.frame.size.width, SCREEN_HEIGHT-20);
//        }
//        if (rightViewController.view.frame.origin.y==0) {
//            rightViewController.view.frame = CGRectMake(rightViewController.view.frame.origin.x, 0, rightViewController.view.frame.size.width, SCREEN_HEIGHT-20);
//        }
//
//        if (self.view.frame.origin.y==0) {
//            self.view.frame = CGRectMake(self.view.frame.origin.x, 20, self.view.frame.size.width, self.view.frame.size.height);
//        }
//    }
//}

//-(void)presentModalViewController:(UIViewController *)modalViewController animated:(BOOL)animated {
//    [super presentModalViewController:modalViewController animated:animated];
//    if (isInTimeTalking) {
//        UINavigationController *navi=self.modalViewController;
//        navi.view.frame=CGRectMake(0, 0, navi.view.frame.size.width, navi.view.frame.size.height);
//    }
//}


-(void)dealloc {
    NSLog(@"RootViewController dealloc");
    [_currViewController release];
    [leftViewController release];
    [rightViewController release];
    [super dealloc];
}

@end
